package com.henry.base.concurrency;

import java.util.Queue;
import java.util.concurrent.*;

public class TestQueuePerformance2 {
    private static final int capacity = 8000000;
    private static final int threadNum = 256;
    private static final int singleCapacity = 1024*1024*16/threadNum;
    public static CountDownLatch latch = new CountDownLatch(threadNum);
//    static long begin;
//    static long end;



    public static class TestQueue implements Runnable {
        static String typ;
        static Queue<Integer> queue =null;

        public static void initQueue(String typ) {
            if("ArrayBlockingQueue".equalsIgnoreCase(typ))
                 queue=new ArrayBlockingQueue<Integer>(capacity);
            else if ("LinkedBlockingQueue".equalsIgnoreCase(typ))
                queue= new LinkedBlockingQueue(capacity);
            else if("ConcurrentLinkedQueue".equalsIgnoreCase(typ))
                queue= new ConcurrentLinkedQueue();
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < singleCapacity; i++) {
//                    Thread.sleep(1);
                    String s = "dasfafafs";
                    int sum=0;
                    for (char c : s.toCharArray()) {
                        byte x = (byte) c;
                        sum+=x;
                    }
                    queue.offer(i);
                }
//                System.out.println("...............");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
    }




    public static void main(String[] args) throws InterruptedException {
        test("LinkedBlockingQueue");
        test("ConcurrentLinkedQueue");
        test("ArrayBlockingQueue");


    }

    public static void test(String typ) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(threadNum);
        TestQueue.initQueue(typ);
        long begin= System.nanoTime();
        for (int i = 0; i < threadNum; i++) {
            pool.submit(new TestQueue());
        }
        latch.await();
        long end= System.nanoTime();
        pool.shutdown();
        latch = new CountDownLatch(threadNum);
        System.out.println(typ+"花费时间："+(end-begin)/1000/1000+"ms");
    }

}
